<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\TopicRequest;
use App\Models\Topic;
use App\Models\User;
use App\Transformers\TopicTransformer;
use Illuminate\Http\Request;
use Log;

class TopicsController extends Controller
{
    public function index(Request $request , Topic $topic)
    {
        $query = $topic->query();
        if($categoryId = $request->category_id){
            $query->where('category_id',$categoryId);
        }
        switch ($request->order){
            case 'recent':
                $query->recent();
                break;
            default:
                $query->recentReplied();
                break;
        }
        $topics = $query->paginate(20);

        return $this->response->paginator($topics,new TopicTransformer());
    }

    public function usersIndex(Request $request,User  $user,Topic $topic)
    {
        $topics = Topic::query()->where('user_id',$user->id)->recent()->paginate(20);
//        $topics = $user->topics()->recent()->paginate(20);

        return $this->response->paginator($topics,new TopicTransformer());
    }

    public function show(Topic $topic)
    {
        return $this->response->item($topic,new TopicTransformer());
    }
    public function store(TopicRequest $request,Topic $topic)
    {
        $topic->fill($request->all());
        $topic->user_id = $this->user()->id;
        $topic->save();

        return $this->response->item($topic,new TopicTransformer())
                ->setStatusCode(201);
    }

    public function update(TopicRequest $request,Topic $topic)
    {
        $this->authorize('update',$topic);
        $topic->title = $request->input('title');
        $topic->body = $request->body;
        $topic->category_id =$request->category_id;
        $topic->save();

        return $this->response->item($topic,new TopicTransformer())
                    ->setStatusCode(201);
    }

    public function destroy(Topic $topic)
    {
        $this->authorize('destroy',$topic);
        $topic->delete();
        return $this->response->noContent();
    }
}
